package com.example.myapplication.tools;

import android.os.CountDownTimer;
import android.widget.TextView;

import java.util.List;

public class TimeUtils2 {
    private CountDownTimer timer;
    long time;
    long spaceTime;
    OnFinishEvent onFinishEvent;
    boolean isRun = false;
    List<String> tempList;
    TextView tvTextView = null;
    long tickTimes = 0;

    public TimeUtils2(long time, long space, OnFinishEvent event) {
        super();
        this.time = time;
        spaceTime = space;
        onFinishEvent = event;
    }

    public void setTextView(TextView tv){
        tvTextView = tv;
    }
    //这是倒计时执行方法
    public void RunTimer() {
        if(timer != null){
            timer.cancel();
            timer = null;
        }
        tickTimes = time / 1000;
        timer = new CountDownTimer(time -1, spaceTime) {
            @Override
            public void onFinish() {
                onFinishEvent.process();
                cancel();
                isRun = false;
            }

            @Override
            public void onTick(long millisUntilFinished) {
                if(tvTextView != null){
                    tickTimes--;
                    tvTextView.setText("" + tickTimes + "");
                }
            }
        }.start();
        isRun = true;
    }
    //这个方法可以在activity或者fragment销毁的时候调用，防止内存泄漏
    public void cancle() {
        if (timer != null) {
            timer.cancel();
            isRun = false;
            timer = null;
        }
    }

    public boolean getIsRun(){
        return isRun;
    }

    public interface OnFinishEvent {
        void process();
    }
    public void setOnFinishEvent(OnFinishEvent event) {
        onFinishEvent = event;
    }
}
